package game_play_strategy.tools;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentValues;
import android.content.Context;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter extends SQLiteOpenHelper{
	public static final String PLAYER_ID = "_id";
	public static final String PLAYER_NAME = "name";
	public static final String PLAYER_EMAIL = "email";
	public static final String PLAYER_IP_ADDRESS = "IP_address";
	public static final String PLAYER_USER_LATITUDE = "user_latitude";
	public static final String PLAYER_USER_LONGITUDE = "user_latitude";
	public static final String PLAYER_CENTER_LATITUDE = "center_latitude";
	public static final String PLAYER_CENTER_LONGITUDE = "center_longitude";
	public static final String PLAYER_SQUARE_NOW = "square_now";
	public static final String PLAYER_IMEI = "imei";
	public static final String PLAYER_WINS = "wins";
	public static final String PLAYER_LOSES = "loses";
	public static final String PLAYER_DRAWS = "draws";
	public static final String PLAYER_TURN = "player_turn";
	public static final String PLAYER_AVAILABLE = "available";

	public static final String HERO_ID = "_id";
	public static final String HERO_ID_LOCAL = "id_hero_local";
	public static final String HERO_ID_PLAYER = "id_player";
	public static final String HERO_NAME = "name";
	public static final String HERO_CLASS = "hero_class";
	public static final String HERO_LEVEL = "level";
	public static final String HERO_EXPERIENCE = "experience";
	public static final String HERO_HEALTH = "health";
	public static final String HERO_MAX_HEALTH = "max_health";
	public static final String HERO_MOVEMENT = "movement";
	public static final String HERO_MAX_MOVEMENT = "max_movement";
	public static final String HERO_STATE = "state";
	public static final String HERO_PRESENT = "present";
	public static final String HERO_SQUARE = "square";
	public static final String HERO_AVATAR = "avatar";
	public static final String HERO_IMEI = "imei";

	private static final String TAG = "DBAdapter";
	//private static final String DATABASE_NAME = "player_db";
	private static final String DATABASE_TABLE_PLAYER = "player";
	private static final String DATABASE_TABLE_HERO = "hero";
	// private static final String DATABASE_TABLE_ABILITY = "ability";

	//private static final int DATABASE_VERSION = 1;
	//private static final String DATABASE_CREATE_PLAYER = "create table contacts (_id integer primary key autoincrement, "
	//		+ "name text not null, email text not null);";
	//private final Context context;
	//private DatabaseHelper DBHelper;
	private SQLiteDatabase db;
	
	//The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/game_play_strategy.tools/databases/";
 
    private static String DB_NAME = "player_db";
 
    //private SQLiteDatabase myDataBase; 
 
    private final Context myContext;

	/*public DBAdapter(Context ctx) {
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}

	private static class DatabaseHelper extends SQLiteOpenHelper 
	{
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			try {
				db.execSQL(DATABASE_CREATE_PLAYER);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS contacts");
			onCreate(db);
		}

	}*/

	// ---opens the database---
	/*public DBAdapter open() throws SQLException {
		db = DBHelper.getWritableDatabase();
		return this;
	}

	// ---closes the database---
	public void close() {
		DBHelper.close();
	}*/
    
    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DBAdapter(Context context) 
    {
    	super(context, DB_NAME, null, 1);
        this.myContext = context;
    }	
 
  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException 
    {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        } else {
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
        this.close();
    }
 
    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){
 
    	SQLiteDatabase checkDB = null;
 
    	try{
    		String myPath = DB_PATH + DB_NAME;
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
 
    	}catch(SQLiteException e){
 
    		//database does't exist yet.
 
    	}
 
    	if(checkDB != null){
 
    		checkDB.close();
 
    	}
 
    	return checkDB != null ? true : false;
    }
 
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{
 
    	//Open your local db as the input stream
    	InputStream myInput = myContext.getAssets().open(DB_NAME);
 
    	// Path to the just created empty db
    	String outFileName = DB_PATH + DB_NAME;
 
    	//Open the empty db as the output stream
    	OutputStream myOutput = new FileOutputStream(outFileName);
 
    	//transfer bytes from the inputfile to the outputfile
    	byte[] buffer = new byte[1024];
    	int length;
    	while ((length = myInput.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}
 
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
 
    }
 
    public void openDataBase() throws SQLException{
 
    	//Open the database
        String myPath = DB_PATH + DB_NAME;
    	db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
 
    }
 
    @Override
	public synchronized void close() {
 
    	    if(db != null)
    		    db.close();
 
    	    super.close();
 
	}
 
	@Override
	public void onCreate(SQLiteDatabase db) 
	{
		
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
	}
 
        // Add your public helper methods to access and get content from the database.
       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
       // to you to create adapters for your views.

	// ---insert a player into the database---
	public long insertPlayer(int id_player, String name, String email,
			String imei, String ip_address, String square_now,
			double center_latitude, double center_longitude,
			double user_latitude, double user_longitude, int player_turn, int available) {
		ContentValues initialValues = new ContentValues();

		initialValues.put(PLAYER_EMAIL, email);
		initialValues.put(PLAYER_NAME, name);
		initialValues.put(PLAYER_ID, id_player);
		initialValues.put(PLAYER_IP_ADDRESS, ip_address);
		initialValues.put(PLAYER_USER_LATITUDE, user_latitude);
		initialValues.put(PLAYER_USER_LONGITUDE, user_longitude);
		initialValues.put(PLAYER_CENTER_LATITUDE, center_latitude);
		initialValues.put(PLAYER_CENTER_LONGITUDE, center_longitude);
		initialValues.put(PLAYER_SQUARE_NOW, square_now);
		initialValues.put(PLAYER_IMEI, imei);
		initialValues.put(PLAYER_TURN, player_turn);
		initialValues.put(PLAYER_AVAILABLE, available);

		return db.insert(DATABASE_TABLE_PLAYER, null, initialValues);
	}
	
	public long insertSimple(String simple) {
		ContentValues initialValues = new ContentValues();

		initialValues.put("simple", simple);

		return db.insert("prosta", null, initialValues);
	}

	// ---insert a hero into the database---
	public long insertHero(String name, int id_hero, int id_hero_local, int id_player,
			String hero_class, String avatar_name, int level, int experience, int health, int max_health,
			int movement, int max_movement, int state, int present,
			String square, String imei) {
		ContentValues initialValues = new ContentValues();

		initialValues.put(HERO_NAME, name);
		initialValues.put(HERO_ID, id_hero);
		initialValues.put(HERO_ID_LOCAL, id_hero_local);
		initialValues.put(HERO_ID_PLAYER, id_hero_local);
		initialValues.put(HERO_CLASS, hero_class);
		initialValues.put(HERO_AVATAR, avatar_name);
		initialValues.put(HERO_LEVEL, level);
		initialValues.put(HERO_EXPERIENCE, experience);
		initialValues.put(HERO_HEALTH, health);
		initialValues.put(HERO_MAX_HEALTH, max_health);
		initialValues.put(HERO_MOVEMENT, movement);
		initialValues.put(HERO_MAX_MOVEMENT, max_movement);
		initialValues.put(HERO_STATE, state);
		initialValues.put(HERO_PRESENT, present);
		initialValues.put(HERO_SQUARE, square);
		initialValues.put(HERO_IMEI, imei);
		

		return db.insert(DATABASE_TABLE_HERO, null, initialValues);
	}

	// ---deletes a particular record: player, hero, ability---
	public boolean deleteRecord(String database, long rowId) {
		if (database.matches("player"))
			return db.delete(DATABASE_TABLE_PLAYER, PLAYER_ID + "=" + rowId,
					null) > 0;
		else if (database.matches("hero"))
			return db.delete(DATABASE_TABLE_HERO, HERO_ID_LOCAL + "=" + rowId, null) > 0;
		else
			return false;
		// else if (database.matches("ability"))
		// return db.delete(DATABASE_TABLE_ABILITY, ABILITY_ID + "=" + rowId,
		// null) > 0;
	}

	// ---retrieves all the contacts---
	// public Cursor getAllHeroes()
	{
		// return db.query(DATABASE_TABLE_HERO, new String[] { KEY_ROWID,
		// KEY_NAME,
		// KEY_EMAIL }, null, null, null, null, null);
	}

	// ---retrieves a particular contact---
	public Cursor getPlayer(int id) throws SQLException {
		Cursor mCursor = db.query(true, DATABASE_TABLE_PLAYER, new String[] {
				PLAYER_ID, PLAYER_NAME, PLAYER_EMAIL, PLAYER_IP_ADDRESS,
				PLAYER_USER_LATITUDE, PLAYER_USER_LONGITUDE,
				PLAYER_CENTER_LATITUDE, PLAYER_CENTER_LONGITUDE,
				PLAYER_SQUARE_NOW, PLAYER_IMEI, PLAYER_TURN, PLAYER_AVAILABLE }, PLAYER_ID + "=" + id,
				null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	public Cursor getHero(long rowId) throws SQLException {
		Cursor mCursor = db.query(true, DATABASE_TABLE_HERO, new String[] {
				HERO_ID, HERO_ID_LOCAL, HERO_ID_PLAYER,
				HERO_NAME, HERO_CLASS, HERO_LEVEL, HERO_EXPERIENCE,
				HERO_HEALTH, HERO_MAX_HEALTH, HERO_MOVEMENT, HERO_MAX_MOVEMENT,
				HERO_STATE, HERO_PRESENT, HERO_SQUARE, HERO_AVATAR }, HERO_ID_LOCAL
				+ "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	

	// ---updates a contact---
	public boolean updatePlayer(int id_player, String name,
			String email, String ip_address, double center_latitude, double center_longitude,
			double user_latitude, double user_longitude, String square_now, String imei, 
			int player_turn, int available) {
		ContentValues args = new ContentValues();

		args.put(PLAYER_ID, id_player);
		args.put(PLAYER_NAME, name);
		args.put(PLAYER_EMAIL, email);
		args.put(PLAYER_IMEI, imei);
		args.put(PLAYER_IP_ADDRESS, ip_address);
		args.put(PLAYER_SQUARE_NOW, square_now);
		args.put(PLAYER_CENTER_LATITUDE, center_latitude);
		args.put(PLAYER_CENTER_LONGITUDE, center_longitude);
		args.put(PLAYER_USER_LATITUDE, user_latitude);
		args.put(PLAYER_USER_LONGITUDE, user_longitude);
		args.put(PLAYER_TURN, player_turn);
		args.put(PLAYER_AVAILABLE, available);

		return db.update(DATABASE_TABLE_PLAYER, args, PLAYER_ID + "=" + id_player,
				null) > 0;
	}

	public boolean updateHero(String name, int id_hero,
			int id_hero_local, String hero_class, String avatar, int level, int experience, int health,
			int max_health, int movement, int max_movement, int state,
			int present, String square) {
		ContentValues args = new ContentValues();

		args.put(HERO_NAME, name);
		//args.put(HERO_ID, id_hero);
		args.put(HERO_ID_LOCAL, id_hero_local);
		args.put(HERO_CLASS, hero_class);
		args.put(HERO_LEVEL, level);
		args.put(HERO_EXPERIENCE, experience);
		args.put(HERO_HEALTH, health);
		args.put(HERO_MAX_HEALTH, max_health);
		args.put(HERO_MOVEMENT, movement);
		args.put(HERO_MAX_MOVEMENT, max_movement);
		args.put(HERO_STATE, state);
		args.put(HERO_PRESENT, present);
		args.put(HERO_SQUARE, square);
		args.put(HERO_AVATAR, avatar);

		return db
				.update(DATABASE_TABLE_HERO, args, HERO_ID_LOCAL + "=" + id_hero_local, null) > 0;
	}
	
	public int getMaxId()
	{
	    String query = "SELECT MAX(_id) FROM player";
	    Cursor cursor = db.rawQuery(query, null);

	    int id = 0;     
	    if (cursor.moveToFirst())
	    {
	        do
	        {           
	            id = cursor.getInt(0);                  
	        } while(cursor.moveToNext());           
	    }
	    return id;
	}
	
	public int getMaxHeroId()
	{
	    String query = "SELECT MAX(_id) FROM hero";
	    Cursor cursor = db.rawQuery(query, null);

	    int id = 0;     
	    if (cursor.moveToFirst())
	    {
	        do
	        {           
	            id = cursor.getInt(0);                  
	        } while(cursor.moveToNext());           
	    }
	    return id;
	}


}